package com.adira.fraud.action;

import java.text.DateFormat;
import java.text.SimpleDateFormat;
import java.util.Calendar;
import java.util.Date;
import java.util.Map;

import org.apache.struts2.interceptor.SessionAware;
import org.hibernate.Query;

import com.adira.fraud.hibernate.HibernateUtil;
import com.adira.fraud.model.pojo.User;
import com.adira.fraud.util.EncryptorManager;
import com.opensymphony.xwork2.ActionSupport;

public class LoginAction extends ActionSupport implements SessionAware {

    private String username;
    private String password;
    private Map<String, Object> sessionAttributes = null;

    public String execute() {
        return SUCCESS;
    }

    public String logout() {
        sessionAttributes.remove("PRIVILEGES");
        sessionAttributes.remove("USER");
        sessionAttributes.remove("userid");
        sessionAttributes.clear();
        return SUCCESS;
    }

    public String login() {
        try {
            DateFormat df = new SimpleDateFormat("yyyy-MM-dd");
            Date today = Calendar.getInstance().getTime();
            String reportDate = df.format(today);
            org.hibernate.Session hibernateSession = HibernateUtil.getSession();
            org.hibernate.Transaction tr = hibernateSession.beginTransaction();
            Query query = hibernateSession.createQuery("FROM User where username like '" + username + "'");
            User userBean = (User) query.uniqueResult();
                 
            System.out.println(EncryptorManager.decrypt(userBean.getPassword())+" "+password);
            
            if (EncryptorManager.decrypt(userBean.getPassword()).equals(password)) {
                    sessionAttributes.put("USER", "1");
                    sessionAttributes.put("userid", userBean.getUserId());
                    sessionAttributes.put("username", userBean.getUsername());
                    sessionAttributes.put("today", reportDate);   
                    return SUCCESS;
                }
            else {
            	addActionError("wrong password or username..");
            	System.out.println("salah password");
                return ERROR;
            }

        } catch (NullPointerException e) {
            e.printStackTrace();
            addActionError("username doesn't exist");
            return ERROR;
        }
    	
    }

    public String getUsername() {
        return username;
    }

    public void setUsername(String username) {
        this.username = username;
    }

    public String getPassword() {
        return password;
    }

    public void setPassword(String password) {
        this.password = password;
    }

    @Override
    public void setSession(Map<String, Object> arg0) {
        this.sessionAttributes = arg0;

    }
}
